package com.spark.common.widget

import android.content.Context
import android.util.AttributeSet
import android.widget.ImageView
import com.spark.common.R

class Switcher(context: Context, attrs: AttributeSet?, defStyle: Int) : ImageView(context, attrs, defStyle) {
    constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0)
    constructor(context: Context) : this(context, null, 0)

    var currState = State.OFF

    var onSwitchChangedListener: OnSwitchChangedListener? = null

    init {
        when (currState) {
            State.OFF -> {
                setImageResource(R.drawable.switcher_off)
            }
            State.ON -> {
                setImageResource(R.drawable.switcher_on)
            }
        }

        setOnClickListener {
            currState = when (currState) {
                State.ON -> {
                    State.OFF
                }
                State.OFF -> {
                    State.ON
                }
            }
            onSwitchChangedListener?.onChanged(this, currState)
        }

    }

    fun getState(): State {
        return currState
    }

    fun update(state: State) {
        currState = state
        invalidate()
    }

    enum class State {
        ON, OFF
    }

    fun addSwitchChangedListener(listener: (Switcher, State) -> Unit) {
        onSwitchChangedListener = object : OnSwitchChangedListener {
            override fun onChanged(switcher: Switcher, state: State) {
                listener(switcher, state)
            }
        }
    }

    interface OnSwitchChangedListener {
        fun onChanged(switcher: Switcher, state: State)
    }
}